package com.yksj.healthtalk.ui.chatting;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.yksj.healthtalk.adapter.ForbiddenWordsAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.ForbidWordEntity;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.DialogUtils;
import com.yksj.healthtalk.utils.WheelUtils;
/**
 * 禁言列表
 * @author zhao
 */
public class ForbiddenWordsListActivity extends BaseFragmentActivity implements OnClickListener{
	String groupChatId;
	PullToRefreshListView mPullToRefreshListView;
	PopupWindow mPopupWindow;
	View mTimeSelectV;
	ForbiddenWordsAdapter mAdapter;
	
	//当前选择的数据项
	CheckBox currentCheckBox;
	ForbidWordEntity currentForbidWordEntity;
	List<ForbidWordEntity> mSourceEntities;//源数据
	
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
		public void onReceive(android.content.Context context, android.content.Intent intent) {
			String action = intent.getAction();
			if(MessagePushService.ACTION_FORBIDDENLIST.equalsIgnoreCase(action)){
				Bundle bundle = intent.getExtras();
				String[] arry = bundle.getStringArray(MessagePushService.BROAD_KEY);
				onParseData(arry);
			}
		};
	};
	
	public void onCreate(Bundle bundle){
		super.onCreate(bundle);
		setContentView(R.layout.forbidden_words_list_layout);
		groupChatId = getIntent().getStringExtra("groupId");
		
		initUI();
		
		initData();
	}
	
	public void onStart(){
		super.onStart();
		onregisterReceiver();
	}
	
	public void onStop(){
		unregisterReceiver(mBroadcastReceiver);
		super.onStop();
	}
	
	public void onBackPressed() {
		sendData();
		finish();
        if(mPopupWindow != null){
        	if(mPopupWindow.isShowing())mPopupWindow.dismiss();
        	mPopupWindow = null;
        }
    }
	
	/**
	 * 注册通知
	 */
	private void onregisterReceiver(){
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(MessagePushService.ACTION_FORBIDDENLIST);
		registerReceiver(mBroadcastReceiver,intentFilter);
	}
	
	/**
	 * 初始化页面
	 */
	private void initUI(){
		initTitle();
		setTitle("禁言");
		
		setBackBtn("返回",this);
		
//		setRight("确定",this);
		
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_listview);
		mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			}
			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				SmartFoxClient.queryForbiddenWordsList(groupChatId);
			}
		});
		mPullToRefreshListView.setRefreshing();
	}
	
	/**
	 * 初始化数据
	 */
	private void initData(){
		showDialog(1000);
		mAdapter = new ForbiddenWordsAdapter(this);
		getListView().setAdapter(mAdapter);
		SmartFoxClient.queryForbiddenWordsList(groupChatId);
		//[{"doctor":{"albums":[],"backGold":0,"bandingState":"","bigIconBackground":"assets/customerIcons/s_zcmale.png","birthday":"2012年07月09日","bodyList":[],"classId":0,"clientIconBackground":"assets/customerIcons/s_zcmale.png","cultureLevel":"","customerAccounts":"2000007","customerGold":"0","customerGroupRel":0,"customerId":"7109","customerLocus":" ","customerNickname":" ","customerSex":1,"distance":0,"doctorBigIconbackground":"","doctorClientBackground":"","doctorEmail":"","doctorHospital":"","doctorMobilePhone":"","doctorOffice":"","doctorRealName":"","doctorSpecially":"","doctorTelephone":"","doctorTitle":"","dwellingPlace":"北京市 东城区","errorCode":0,"flag":"","gameLevel":0,"infoVersion":"1","interestsList":[],"latitude":0,"list":[],"longitude":0,"mark":0,"marryFlag":" ","metier":"","microBlogUID":"","onlineState":"","personalNarrate":" ","relationType":0,"roleId":1,"sessionCode":"","ticketFlag":""}}]
	}
	
	private ListView getListView(){
		return mPullToRefreshListView.getRefreshableView();
	}

	/**
	 * 响应数据解析
	 * @param strings
	 */
	private void onParseData(String[] strings){
		if(strings.length == 0){
			removeDialog(1000);
			if(mPullToRefreshListView.isRefreshing()){
				mPullToRefreshListView.onRefreshComplete();
			}
		}else{
			new DataParseAsynTask().execute(strings);
		}
	}
	
	/**
	 * 解析数据
	 */
	private List<ForbidWordEntity> parseResultData(String[] dataStr){
		List<ForbidWordEntity> list = new ArrayList<ForbidWordEntity>();
		if(dataStr != null){
			for (String string : dataStr) {
				try{
					JSONObject jsonObject = new JSONObject(string);
					JSONObject jsonObject2 = jsonObject.getJSONObject("doctor");
					
					String clientIconbackground = jsonObject2.getString("clientIconBackground");
					String duomeiNumber = jsonObject2.getString("customerAccounts");
					String nickname = jsonObject2.getString("customerNickname");
					String sex = jsonObject2.getString("customerSex");
					String customerid = jsonObject2.getString("customerId");
					
					String time = "0";
					if(jsonObject.has("time")){
						time = jsonObject.getString("time");
					}
					ForbidWordEntity forbidWordEntity = new ForbidWordEntity();
					forbidWordEntity.setDuomeiNumber(duomeiNumber);
					forbidWordEntity.setHeaderPath(clientIconbackground);
					forbidWordEntity.setName(nickname);
					forbidWordEntity.setSex(sex);
					forbidWordEntity.setUserId(customerid);
					forbidWordEntity.setTime(time);
					list.add(forbidWordEntity);
				}catch(JSONException e){
					e.printStackTrace();
				}
			}
		}
//		mSourceEntities = new ArrayList<ForbidWordEntity>(list);
		mSourceEntities = deepCopy(list);
//		mSourceEntities = (ArrayList)((ArrayList<ForbidWordEntity>)list).clone();
		return list;
	}
	
	/**
	 * 深度拷贝
	 * @param src
	 * @return
	 */
	private List deepCopy(List src){
		List dest = null;
		try{
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();       
			ObjectOutputStream out = new ObjectOutputStream(byteOut);       
			out.writeObject(src);       

			ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());       
			ObjectInputStream in =new ObjectInputStream(byteIn);       
			dest = (List)in.readObject();
			if(in != null)in.close();
			if(byteOut != null)byteOut.close();
		}catch(IOException e){
		}catch(ClassNotFoundException e){
		}
		return dest;       
	}  
	
	/**
	 * 
	 * 发送数据
	 * 
	 */
	private void sendData(){
		Collection<String> collection = new ArrayList<String>();
		JSONObject jsonObject = new JSONObject();
		List<ForbidWordEntity> list = mAdapter.getDataList();
		for (int i = 0; i < list.size(); i++) {
			ForbidWordEntity forbidWordEntity = list.get(i);
			String time =  forbidWordEntity.getTime();
			String userId =  forbidWordEntity.getUserId();
			ForbidWordEntity forbidWordEntity1 = mSourceEntities.get(i);
			if(!time.equals(forbidWordEntity1.getTime())){//不相等表示有改动
				try{
					jsonObject.put("customerid", userId);
					jsonObject.put("time", time);
					collection.add(jsonObject.toString());
				}catch(JSONException e){
					e.printStackTrace();
				}
			}
		}
		if(collection.size() != 0){
			SmartFoxClient.updateForbiddenWordsList(groupChatId,collection);
		}
	}
	
	private void onShowSelectTimeWindow(){
		if(mTimeSelectV == null){
			mTimeSelectV = getLayoutInflater().inflate(R.layout.window_forbidden_words_menu_layout,null);
			mTimeSelectV.findViewById(R.id.time_one_hour).setOnClickListener(this);
			mTimeSelectV.findViewById(R.id.time_three).setOnClickListener(this);
			mTimeSelectV.findViewById(R.id.time_ten).setOnClickListener(this);
			mTimeSelectV.findViewById(R.id.time_thirty).setOnClickListener(this);
			mTimeSelectV.findViewById(R.id.time_one_hour).setOnClickListener(this);
			mTimeSelectV.findViewById(R.id.time_six_hour).setOnClickListener(this);
			mTimeSelectV.findViewById(R.id.time_twelve_hour).setOnClickListener(this);
			mTimeSelectV.findViewById(R.id.invite_cancel).setOnClickListener(this);
			mPopupWindow = new PopupWindow(mTimeSelectV, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
				@Override
				public void onDismiss() {
					if("0".equals(currentForbidWordEntity.getTime())){
						currentCheckBox.setChecked(false);
					}
					currentCheckBox = null;
					currentForbidWordEntity = null;
				}
			});
		}
		WheelUtils.setPopeWindow(this,mTimeSelectV,mPopupWindow);
	}
	
	/**
	 * 数据解析线程
	 * @author zhao
	 */
	class DataParseAsynTask extends AsyncTask<String[],String,List<ForbidWordEntity>>{
		@Override
		protected List<ForbidWordEntity> doInBackground(String[]... params) {
			return parseResultData(params[0]);
		}
		@Override
		protected void onPostExecute(List<ForbidWordEntity> list) {
			removeDialog(1000);
			mAdapter.addData(list);
			if(mPullToRefreshListView.isRefreshing()){
				mPullToRefreshListView.onRefreshComplete();
			}
		}
	}
	
	/**
	 * 时间选择
	 * @param time
	 */
	private void onSelectTime(int time){
		//取消
		if(time == 0){
			currentCheckBox.setChecked(false);
		}else{
			currentForbidWordEntity.setTime(String.valueOf(time));
			mAdapter.notifyDataSetChanged();
		}
		mPopupWindow.dismiss();
	}
	

	
	public void onSwitchClick(ForbidWordEntity forbidWordEntity,CheckBox checkBox){
		currentForbidWordEntity = forbidWordEntity;
		currentCheckBox = checkBox;
		if(checkBox.isChecked()){
			onShowSelectTimeWindow();
		}else{
			currentForbidWordEntity.setTime("0");
			mAdapter.notifyDataSetChanged();
		}
	}
	
	public Dialog onCreateDialog(int id){
		switch(id){
		case 1000:
			return DialogUtils.getLoadingDialog(this,getString(R.string.dataload));
		}
		return super.onCreateDialog(id);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.time_three:
			onSelectTime(3);
			break;
		case R.id.time_ten:
			onSelectTime(10);
			break;
		case R.id.time_thirty:
			onSelectTime(30);
			break;
		case R.id.time_one_hour:
			onSelectTime(1*60);
			break;
		case R.id.time_six_hour:
			onSelectTime(6*60);
			break;
		case R.id.time_twelve_hour:
			onSelectTime(12*60);
			break;
		case R.id.invite_cancel:
			onSelectTime(0);
			break;
		}
	}
}
